<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户编码" prop="clientCode">
        <el-input
          v-model="queryParams.clientCode"
          placeholder="请输入客户编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户简称" prop="clientNick">
        <el-input
          v-model="queryParams.clientNick"
          placeholder="请输入客户简称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户英文名称" prop="clientEn" style="margin-bottom: 5; white-space: nowrap;">
        <el-input
          v-model="queryParams.clientEn"
          placeholder="请输入客户英文名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="enableFlag">
        <el-input
          v-model="queryParams.enableFlag"
          placeholder="请输入是否启用"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['client:client:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['client:client:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['client:client:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['client:client:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="clientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="客户ID" align="center" prop="clientId" /> -->
      <el-table-column label="客户编码" align="center" prop="clientCode" />
      <el-table-column label="客户名称" align="center" prop="clientName" />
      <el-table-column label="客户简称" align="center" prop="clientNick" />
      <el-table-column label="客户类型" align="center" prop="clientType">
        <template #default="scope">
          {{ scope.row.clientType === 'ENTERPRISE' ? '企业用户' : '个人' }}
        </template>
      </el-table-column>

      <el-table-column label="客户电话" align="center" prop="tel" />
      <el-table-column label="联系人1" align="center" prop="contact1" />
      <el-table-column label="联系人1-电话" align="center" prop="contact1Tel" />
          <el-table-column label="是否启用" align="center" prop="enableFlag" >
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.enableFlag ==='Y'">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['client:client:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['client:client:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户对话框 -->
   <el-dialog :title="title" v-model="open" width="880px" append-to-body>
  <el-form ref="clientRef" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="客户编码" prop="clientCode">
        <el-input v-model="form.clientCode" :disabled="autoCode" placeholder="请输入客户编码" clearable />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="自动生成">
        <el-switch v-model="autoCode" active-text="自动生成" @change="handleAutoCode" />
      </el-form-item>
    </el-col>
  </el-row>
    <el-form-item label="客户名称" prop="clientName">
  <el-input v-model="form.clientName" placeholder="请输入客户名称" clearable />
    </el-form-item>


    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="客户简称" prop="clientNick">
          <el-input v-model="form.clientNick" placeholder="请输入客户简称" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客户英文名称" prop="clientEn">
          <el-input v-model="form.clientEn" placeholder="请输入客户英文名称" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客户类型" prop="clientType">
          <el-select v-model="form.clientType" placeholder="请选择客户类型" clearable>
            <el-option v-for="(item, index) in clientTypeOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="客户简介" prop="clientDes">
      <el-input type="textarea" v-model="form.clientDes" placeholder="请输入客户简介" :autosize="{minRows: 3, maxRows: 4}" />
    </el-form-item>

    <el-form-item label="客户地址" prop="address">
      <el-input type="textarea" v-model="form.address" placeholder="请输入客户地址" :autosize="{minRows: 3, maxRows: 4}" />
    </el-form-item>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="客户官网地址" prop="website">
          <el-input v-model="form.website" placeholder="请输入客户官网地址" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客户邮箱地址" prop="email">
          <el-input v-model="form.email" placeholder="请输入客户邮箱地址" clearable />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="客户电话" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入客户电话" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客户LOGO" prop="clientLogo">
          <el-input v-model="form.clientLogo" placeholder="请输入客户LOGO" clearable />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="联系人1" prop="contact1">
          <el-input v-model="form.contact1" placeholder="请输入联系人1" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="联系人1-电话" prop="contact1Tel">
          <el-input v-model="form.contact1Tel" placeholder="请输入联系人1电话" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="联系人1-邮箱" prop="contact1Email">
          <el-input v-model="form.contact1Email" placeholder="请输入联系人1邮箱" clearable />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="联系人2" prop="contact2">
          <el-input v-model="form.contact2" placeholder="请输入联系人2" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="联系人2-电话" prop="contact2Tel">
          <el-input v-model="form.contact2Tel" placeholder="请输入联系人2电话" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="联系人2-邮箱" prop="contact2Email">
          <el-input v-model="form.contact2Email" placeholder="请输入联系人2邮箱" clearable />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入社会信用代码" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否有效" prop="enableFlag">
          <el-radio-group v-model="form.enableFlag">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="备注" prop="remark">
      <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" :autosize="{minRows: 3, maxRows: 4}" />
    </el-form-item>

 <el-tabs v-if="form.clientId" v-model="activeTab">
  <el-tab-pane label="产品清单" name="product">
    <el-table :data="form.productList || []">
      <el-table-column prop="productCode" label="物料编码" />
      <el-table-column prop="productName" label="物料名称" />
      <el-table-column prop="model" label="规格型号" />
      <el-table-column prop="unit" label="单位" />
    </el-table>
  </el-tab-pane>

  <el-tab-pane label="销售记录" name="sale">
    <el-table :data="form.saleRecordList || []">
      <el-table-column prop="saleCode" label="销售单号" />
      <el-table-column prop="saleDate" label="销售日期" />
      <el-table-column prop="amount" label="数量" />
    </el-table>
  </el-tab-pane>
</el-tabs>


  </el-form>

  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </template>
</el-dialog>

  </div>
</template>

<script setup name="Client">
import { listClient, getClient, delClient, addClient, updateClient } from "@/api/client/client"
// 客户类型下拉选项
const clientTypeOptions = [
  { label: '企业用户', value: 'ENTERPRISE' },
  { label: '个人', value: 'INDIVIDUAL' }
]


const { proxy } = getCurrentInstance()

const clientList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    clientCode: null,
    clientName: null,
    clientNick: null,
    clientEn: null,
    enableFlag: null,
  },
  rules: {
    clientCode: [
      { required: true, message: "客户编码不能为空", trigger: "blur" }
    ],
    clientName: [
      { required: true, message: "客户名称不能为空", trigger: "blur" }
    ],
    enableFlag: [
      { required: true, message: "是否启用不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
// 是否自动生成编码
const autoCode = ref(false)

// 自动生成编码的逻辑
function handleAutoCode(val) {
  if (val) {
    // 这里你可以写生成规则，例如时间戳 + 随机数
    form.value.clientCode = "C" + Date.now()
  } else {
    form.value.clientCode = null // 切换回手动时清空
  }
}


/** 查询客户列表 */
function getList() {
  loading.value = true
  listClient(queryParams.value).then(response => {
    clientList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    clientId: null,
    clientCode: null,
    clientName: null,
    clientNick: null,
    clientEn: null,
    clientDes: null,
    clientLogo: null,
    clientType: null,
    address: null,
    website: null,
    email: null,
    tel: null,
    contact1: null,
    contact1Tel: null,
    contact1Email: null,
    contact2: null,
    contact2Tel: null,
    contact2Email: null,
    creditCode: null,
    enableFlag: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    // 子表：产品清单
    productList: [],
    // 子表：销售记录
    saleRecordList: []
  }
  proxy.resetForm("clientRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.clientId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.productList = []
  form.value.saleRecordList = []
  open.value = true
  title.value = "添加客户"
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _clientId = row.clientId || ids.value
  //修改的时候显示
  getClient(_clientId).then(response => {
    form.value = response.data
    // 如果接口返回没有字段，手动兜底
    form.value.productList = response.data.productList || []
    form.value.saleRecordList = response.data.saleRecordList || []
    open.value = true
    title.value = "修改客户"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["clientRef"].validate(valid => {
    if (valid) {
      if (form.value.clientId != null) {
        updateClient(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addClient(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _clientIds = row.clientId || ids.value
  proxy.$modal.confirm('是否确认删除客户编号为"' + _clientIds + '"的数据项？').then(function() {
    return delClient(_clientIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('client/client/export', {
    ...queryParams.value
  }, `client_${new Date().getTime()}.xlsx`)
}

getList()

</script>
